/* 
 * Author: anand
 * 
 */

#include "playlist_items.h"

playlist_items::playlist_items(int playlistid) {
    _dbhelper = dbhelper::get_helper();
    _playlistid = playlistid;
    _items = new std::vector<playlist_item>;
    
    //Load the items up
    std::string sql = PLAYLISTITEMS_GET_SQL;
    sql.replace(sql.find("?"),1,path_util::convert_to_string(_playlistid));
    result_set * result = _dbhelper->get_row_map(sql.c_str() );
    result_set::const_iterator p = result->begin();
    while(p!=result->end()){
        playlist_item *item = new playlist_item;
        item->set_path((**p)["path"]);
        item->set_name((**p)["name"]);
        item->set_position(  atof( (**p)["position"].c_str() ) );
        item->set_playcount(atoi( (**p)["playcount"].c_str() ) );
		item->set_id(atoi( (**p)["id"].c_str() ) );
        _items->push_back(*item);
        p++;
    }
    delete result;

}

void playlist_items::show_playlist_items()
{
    std::cout<<"Playlist: \n";
    for(int i = 0;i<_items->size();i++){
        std::cout<<i+1<<" : "<<_items->at(i).get_name()<<"\n";
    }
}
void playlist_items::add_playlist_item(playlist_item *item)
{
	playlist_item *additem = new playlist_item(*item);
	additem->save();
    update_relation(additem,true);
	_items->push_back(*additem);
	sort_playlist();
}
void playlist_items::sort_playlist()
{
	sort(_items->begin(),_items->end());
}
void playlist_items::update_relation(playlist_item *item, bool save)
{
	if(save)
	{
		std::string sql = PLAYLISTITEMS_SAVE_SQL;
		sql.replace(sql.find("?"),1,path_util::convert_to_string(_playlistid));
		sql.replace(sql.find("?"),1,path_util::convert_to_string(item->get_id()));
		sql.replace(sql.find("?"),1,path_util::convert_to_string(item->get_position()));
		_dbhelper->raw_execute(sql.c_str());

	}
	else
	{
		std::string sql = PLAYLISTITEMS_UPDATE_SQL;
		sql.replace(sql.find("?"),1,path_util::convert_to_string(item->get_position()));
		sql.replace(sql.find("?"),1,path_util::convert_to_string(_playlistid));
		sql.replace(sql.find("?"),1,path_util::convert_to_string(item->get_id()));
		_dbhelper->raw_execute(sql.c_str());
	}

}
playlist_items::playlist_items(const playlist_items& orig) {
}

playlist_items::~playlist_items() {
    delete _items;
}

